package com.zsj.queue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zsj
 * @Version 1.0
 * @Date 2024/3/31 13:22
 * @Description 单锁实现队列
 */
public class BlockQueueSingleLock<E> implements Queue<E> {

    private E[] array;
    private int tail;
    private int size;
    ReentrantLock lock = new ReentrantLock();
    Condition tallWaits = lock.newCondition();

    @Override
    public boolean offer(E value) throws InterruptedException {
        lock.lockInterruptibly();//表示锁 可以被打断
        try {
            if (isFull()) {
                tallWaits.await();//阻塞当前线程
                return false;
            }//满了无法添加
            array[tail] = value;
            if (++tail == array.length) tail = 0;
            size++;
        } finally {
            lock.unlock();
        }
        return false;
    }

    @Override
    public E poll() {
        return null;
    }

    @Override
    public E peek() {
        return null;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }
}
